import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getKeyList } from "@pureadmin/utils";
import { usePublicHooks } from "@/views/system/hooks";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted, toRaw, h } from "vue";
import { addDialog, closeDialog } from "@/components/ReDialog";
import descriptionForm from "./description.vue";
import {
  getOperationLogsList,
  deleteOperationLog,
  exportOperationLogExcel,
  deleteAllOperationLog
} from "@/api/system/log";
export function useRole(tableRef: Ref) {
  const form = reactive({
    module: "",
    status: "",
    beginTime: "",
    endTime: "",
    username: "",
    operationTime: ""
  });
  const defaultSort = reactive({
    prop: "",
    order: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const { tagStyle } = usePublicHooks();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "编号",
      prop: "id",
      minWidth: 90
    },
    {
      label: "所属模块",
      prop: "requestModule",
      minWidth: 140
    },
    {
      label: "操作类型",
      prop: "businessType",
      minWidth: 120,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={row.businessTypeCssTag} effect="plain">
          {row.businessTypeStr}
        </el-tag>
      )
    },
    {
      label: "请求方式",
      prop: "requestMethod",
      minWidth: 120
    },
    {
      label: "操作 IP",
      prop: "operatorIp",
      minWidth: 100
    },
    {
      label: "操作地点",
      prop: "operatorLocation",
      minWidth: 140
    },
    {
      label: "操作人员",
      prop: "username",
      minWidth: 100
    },
    {
      label: "操作概要",
      prop: "requestDesc",
      width: 140,
      showOverflowTooltip: true
    },
    {
      label: "操作状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === 1 ? "成功" : "失败"}
        </el-tag>
      )
    },
    {
      label: "操作时间",
      prop: "operationTime",
      sortable: "custom",
      minWidth: 180,
      formatter: ({ operationTime }) =>
        dayjs(operationTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    getOperationLogList();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    getOperationLogList();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const ids = getKeyList(curSelected, "id");
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    deleteOperationLog(ids).then(data => {
      data &&
        message(`已删除日志编号为 ${getKeyList(curSelected, "id")} 的数据`, {
          type: "success"
        });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    });
  }
  /** 导出全部日志 */
  function exportAllExcel() {
    const fileName = "操作日志.xlsx";
    const query = getOpertionForm();
    exportOperationLogExcel(fileName, query);
  }

  function getOpertionForm(): opertionQuery {
    const [beginTime, endTime] =
      form.operationTime?.length === 2
        ? [form.operationTime[0], form.operationTime[1]]
        : [undefined, undefined];

    const query = {
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
      username: form.username,
      status: form.status,
      module: form.module,
      beginTime,
      endTime,
      orderColumn: defaultSort.prop,
      orderDirection: defaultSort.order
    };
    return query;
  }

  /** 清空日志 */
  function clearAll() {
    deleteAllOperationLog();
    message("已删除所有日志数据", {
      type: "success"
    });
    onSearch();
  }
  function openDialog(row) {
    addDialog({
      title: "日志详情",
      width: "60%",
      draggable: true,
      fullscreenIcon: false,
      closeOnClickModal: true,
      contentRenderer: () => h(descriptionForm, toRaw(row)),
      footerButtons: [
        {
          label: "关闭",
          text: true,
          size: "large",
          bg: true,
          btnClick: ({ dialog: { options, index } }) => {
            closeDialog(options, index);
          }
        }
      ]
    });
  }
  function handleSortChange({ prop, order }) {
    defaultSort.prop = prop;
    defaultSort.order = order;
    getOperationLogList();
  }
  async function getOperationLogList() {
    loading.value = true;
    const query = getOpertionForm();
    const data = await getOperationLogsList(query);
    dataList.value = data.list;
    pagination.total = data.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  async function onSearch() {
    pagination.currentPage = 1;
    pagination.pageSize = 10;
    getOperationLogList();
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onSearch,
    clearAll,
    resetForm,
    onbatchDel,
    exportAllExcel,
    openDialog,
    handleSizeChange,
    handleSortChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
